<template>
    <view class="goods-details">
        <view class="contain" v-if="!isNull" id="goods" @touchstart="isTouchStart = true">
            <bubble-tips top="200rpx"></bubble-tips>

            <product-swiper :imgUrls="swiperList" :video="goodsDetail.video"></product-swiper>
            <view
                class="goods-info bg-white round-box m-x-20"
                :style="{
                    'margin-top': goodsType != 0 || goodsDetail.member_price ? '-90rpx' : '30rpx'
                }"
            >
                <view class="info-header flex">
                    <view class="price flex flex-1">
						<view class="need-gouwuquan" v-if="$Route.query.page == 'gouwuquan'">
						    <text>19999</text>
							购物券
						</view>
                        <view class="primary m-r-10" v-else>
                            <price-format
                                :first-size="46"
                                :second-size="32"
                                :subscript-size="32"
                                :price="goodsDetail.min_price"
                            ></price-format>
                        </view>
                        <view class="muted md shichang-box">
							市场价：
                            <price-format
                                :price="goodsDetail.market_price"
                                v-if="goodsDetail.market_price != 0"
                            ></price-format>
                        </view>
                    </view>
					<view>
					    <view class="flex fenxiang-btn" @tap="showShareBtn = true">
					        <u-icon name="share" size="26" />
					        <text>分享</text>
					    </view>
					</view>
                </view>
                <view class="flex m-t-20">
                    <view class="name lg bold">{{ goodsDetail.name }}</view>
                </view>
                <view class="flex row-between lighter" style="padding: 20rpx 0">
					<text class="jifen-box">购买可获得145积分</text>
                    <text class="yue-xiao">月销量: {{ goodsDetail.sales_sum }}套</text>
                </view>
            </view>
            <view
                v-if="!goodsType"
                class="spec flex bg-white m-t-20 round-box m-x-20"
                @tap="showSpecFun(0)"
            >
                <view class="text muted">已选</view>
                <view class="line-1 m-r-20 flex-1">{{
                    checkedGoods.spec_value_str || '默认'
                }}</view>
                <u-icon name="arrow-right"></u-icon>
            </view>
            <view
                class="evaluation bg-white m-t-20 round-box m-x-20"
                id="evaluation"
            >
                <router-link
                    :to="{
                        path: '/bundle/pages/all_comments/all_comments',
                        query: { id: goodsDetail.id }
                    }"
                >
                    <view class="title flex row-between">
                        <view>
                            <text class="balck md m-r-10">评价（0）</text>
                        </view>
                        <view class="flex">
                            <text class="lighter xs">暂无评价</text>
                        </view>
                    </view>
                </router-link>
            </view>
			
			<view class="shouhou-box">
				<view class="shouhou-title">
					售后保障
				</view>
				<view class="miaoshu">
					<image src="../../static/images/duihao.png" mode=""></image>
					7天无理由退货
					<image src="../../static/images/duihao.png" mode=""></image>
					售后维修
					<image src="../../static/images/duihao.png" mode=""></image>
					极速退款
				</view>
			</view>

            <view class="details m-t-20 bg-white round-box m-x-20" id="details">
                <view class="title">商品详情</view>
                <view class="content">
                    <u-parse
                        :html="goodsDetail.content"
                        :lazy-load="true"
                        :show-with-animation="true"
                    ></u-parse>
                </view>
            </view>
            <view :class="['footer', 'bg-white', 'fixed', $Route.query.page != 'gouwuquan' ? 'flex' : 'flex-center']">
				<button
					v-if="$Route.query.page != 'gouwuquan'"
				    class="btn flex-col col-center row-center"
				    hover-class="none"
				    @tap="collectGoodsFun"
				>
				    <image
				        class="icon-md"
				        src="/static/images/icon_collection_s.png"
				    >
				    </image>
				    <text class="xxs lighter">首页</text>
				</button>
                <template>
					<view class="jiaru-goumai">
						<view class="goumai-box" @tap="showSpecFun(2)">{{
						    $Route.query.page == 'gouwuquan' ? '立即兑换' : btnText.red
						}}</view>
					</view>
                </template>
                <!-- <view class="consult-btn br60 white m-r-20 md m-l-20" @tap="handleConsult">
                    咨询商家
                </view> -->
            </view>
        </view>
        <view v-else>
            <view class="details-null flex-col col-center">
                <image class="img-null" src="/static/images/goods_null.png"></image>
                <view class="xs muted">该商品已下架或不存在，去逛逛别的吧~</view>
            </view>
            <goods-column></goods-column>
        </view>
        <!-- 规格 -->
        <spec-popup
            :show="showSpec"
            :is-seckill="goodsType == 1"
            :goods="goodsDetail"
            @close="showSpec = false"
            :show-add="popupType == 1 || popupType == 0"
            :show-buy="popupType == 2 || popupType == 0"
            :show-stock="goodsDetail.is_show_stock == 1"
            :show-confirm="popupType == 3"
            @buynow="onBuy"
            :type="goodsDetail.type"
            :group="!!isGroup"
            @addcart="onAddCart"
            @change="onChangeGoods"
            :red-btn-text="btnText.red"
            :yellow-btn-text="btnText.yellow"
            @confirm="onConfirm"
        ></spec-popup>

        <!-- 分享海报 -->
        <share-popup
            v-model="showShareBtn"
            :share-id="id"
            pagePath="pages/goods_details/goods_details"
            type="1"
            :config="{
                avatar: userInfo.avatar,
                nickname: userInfo.nickname,
                image: goodsDetail.poster || goodsDetail.image,
                price: goodsDetail.min_price,
                marketPrice: goodsDetail.market_price,
                name: team.share_title || goodsDetail.name
            }"
        />

        <share-popup
            :show="showShareBtn"
            @close="showShareBtn = false"
            :goods-id="id"
            :img-url="goodsDetail.image"
            :summary="goodsDetail.remark"
            :share-title="goodsDetail.name"
        ></share-popup>
        <!-- 悬浮按钮 -->
        <!-- <float-tab></float-tab> -->
        <!-- 佣金显示 -->
        <view class="share-money" :class="{ show: showCommission && enableCommission }">
            <view class="row-end">
                <view class="share-close row-center" @tap="showCommission = false">
                    <u-icon name="close" size="16" color="#fff"></u-icon>
                </view>
            </view>
            <view class="share-con mt10" @tap="showShareBtn = true">
                <view class="primary" style="font-size: 45rpx">
                    {{ distribution.earnings }}<text class="xs">元</text>
                </view>
                <view class="lighter xxs"> 好友下单最高可赚 </view>
            </view>
        </view>
        <loading-view v-if="isFirstLoading"></loading-view>
    </view>
</template>
<script>
import { getGoodsDetail, addCart } from '@/api/store'
import { collectGoods } from '@/api/user'
import { getCouponList, teamCheck } from '@/api/activity'
import { mapActions, mapGetters } from 'vuex'
import { toLogin } from '@/utils/login'
import Cache from '@/utils/cache'
import { strToParams, arraySlice, getRect, getcu } from '@/utils/tools'
const app = getApp()
export default {
    data() {
        return {
            active: 0,
            isTouchStart: false,
            topArr: [],
            isFirstLoading: true,
            isNull: false,
            isGroup: 0,
            showSpec: false,
            showCoupon: false,
            showShareBtn: false,
            showCommission: true,
            popupType: '',
            swiperList: [],
            goodsDetail: {},
            goodsType: 0,
            checkedGoods: {},
            comment: {},
            countTime: 0,
            team: {},
            teamFound: [],
            navStyle: {
                backBg: 0.4,
                backgroundBg: 0,
                backColor: 'rgba(256,256,256,1)'
            },
            id: '',
            shop: {},
            // 分销
            distribution: {}
        }
    },
    onLoad() {
        const options = this.$Route.query
        if (options && options.scene) {
            const scene = strToParams(decodeURIComponent(options.scene))
            options.id = scene.id
        }
        this.id = options.id
        this.getGoodsDetailFun()
        this.getCartNum()
    },
    onPageScroll(e) {
        const top = uni.upx2px(500)
        const { scrollTop } = e
        const percent = scrollTop / top
        this.navStyle.backgroundBg = percent
        this.navStyle.backBg = 0.4 * (0.5 - percent)
        this.navStyle.backColor =
            percent < 0.5
                ? 'rgba(256,256,256,' + (0.5 - percent) * 2 + ')'
                : 'rgba(0,0,0,' + (percent - 0.5) * 2 + ')'
        if (!this.isTouchStart) return
        const topList = this.topArr
            .map((item, index) => ({
                index,
                top: item
            }))
            .filter((item) => item.top <= scrollTop)

        if (topList.length) {
            const index = topList.sort((a, b) => b.top - a.top)[0].index
            if (this.active == index) return
            this.active = index
        }
    },
    methods: {
        ...mapActions(['getCartNum', 'wxShare']),
        changeActive(index) {
            this.isTouchStart = false

            uni.pageScrollTo({
                scrollTop: this.topArr[index],
                duration: 200
            })
        },
        getRectInfo() {
            if (this.topArr.length) return
            getRect('#goods').then((res) => {
                this.topArr[0] = res.top - this.navHeight
            })
            getRect('#evaluation').then((res) => {
                this.topArr[1] = res.top - this.navHeight
            })
            getRect('#details').then((res) => {
                this.topArr[2] = res.top - this.navHeight
            })
        },
        async getGoodsDetailFun() {
            const { data, code } = await getGoodsDetail({
                goods_id: this.id
            })
            console.log('detail', data)
            if (code == 1) {
                const { goods_image, content, comment, like, activity, shop, distribution } = data
                let { info, type, team, found, end_time } = activity //秒杀时间
                console.log(activity)
                // 拼团的结束时间-现在的时间 = 剩余的时间
                let time = end_time
                    ? end_time - Date.now() / 1000
                    : info
                    ? info.activity_end_time - Date.now() / 1000
                    : 0

                if (found) {
                    found = arraySlice(found, [], 2)
                }
                this.distribution = distribution || {}
                this.shop = shop
                //TODO处理富文本
                // #ifndef APP-PLUS
                data.content = content.replaceAll('width: 750px', '')
                // #endif
                // #ifdef APP-PLUS
                data.content = content.replace(/width: 750px/g, '')
                // #endif
                this.goodsDetail = data
                this.swiperList = goods_image
                this.comment = comment || {}
                this.countTime = time
                this.goodsType = type
                this.team = info ? info : {}
                this.teamFound = found ? found : []
                // #ifdef H5
                const options = {
                    shareTitle: this.team.share_title || data.name,
                    shareImage: data.image || '',
                    shareDesc: this.team.share_intro || data.remark
                }
                this.wxShare(options)
                // #endif
                this.$nextTick(() => {
                    // 滚动到顶部，防止h5端出现问题
                    uni.pageScrollTo({
                        scrollTop: 0,
                        duration: 0
                    })
                    this.isFirstLoading = false
                    this.getRectInfo()
                })
            } else {
                this.isNull = true
                this.isFirstLoading = false
            }
        },

        async collectGoodsFun() {
            if (!this.isLogin) return this.$Router.push('/pages/login/login')
            const {
                goodsDetail: { is_collect }
            } = this
            const { msg, code } = await collectGoods({
                goods_id: this.id
            })
            if (code == 1) {
                {
                    this.$toast({
                        title: msg
                    })
                }
                this.goodsDetail.is_collect = !this.goodsDetail.is_collect
                // this.getGoodsDetailFun()
            }
        },
        showCouponFun() {
            if (!this.isLogin) return toLogin()
            this.showCoupon = true
        },
        onChangeGoods(e) {
            this.checkedGoods = e.detail
        },
        showSpecFun(type, id) {
            if (this.goodsType == 2 && [2, 3].includes(type)) {
                this.isGroup = 1
                this.foundId = id
            } else {
                this.isGroup = 0
                this.foundId = ''
            }
            this.popupType = type
            this.showSpec = true
        },
        onBuy(e) {
            if (!this.isLogin) return this.$Router.push('/pages/login/login')
            const { id, goodsNum } = e.detail
            const params = {
                goods: [
                    {
                        item_id: id,
                        num: goodsNum,
                        goods_id: this.id,
                        shop_id: this.shop.id,
                        delivery_type: this.goodsDetail.default_delivery_type
                    }
                ],
                type: 'buy',
                goodsType: this.goodsDetail.type
            }
            this.showSpec = false
            this.goodsType == 2 ? (params.teamId = this.team.id) : ''
            this.foundId ? (params.foundId = this.foundId) : ''
            console.log(params, 2222)
            this.$Router.push({
                path: '/pages/confirm_order/confirm_order',
                query: {
                    data: params,
					page: this.$Route.query.page
                }
            })
        },

        onConfirm(e) {
            const {
                team: { team_id }
            } = this

            teamCheck({
                team_id: this.foundId,
                // found_id: this.foundId,
                goods_id: e.detail.goods_id,
                item_id: e.detail.id,
                count: e.detail.goodsNum
            }).then((res) => {
                if (res.code == 1) {
                    this.onBuy(e)
                }
            })
        },

        async onAddCart(e) {
            if (!this.isLogin) return this.$Router.push('/pages/login/login')

            if (this.goodsType == 2) {
                // 拼团单独购买
                const params = {
                    goods: [
                        {
                            item_id: e.detail.id,
                            num: e.detail.goodsNum,
                            delivery_type: this.goodsDetail.default_delivery_type,
                            goods_id: this.id,
                            shop_id: this.shop.id
                        }
                    ],
                    type: 'buy',
                    goodsType: this.goodsDetail.type
                }
                this.$Router.push({
                    path: '/pages/confirm_order/confirm_order',
                    query: {
                        data: params
                    }
                })
                return
            }

            const { id, goodsNum } = e.detail
            const { code, data, msg } = await addCart({
                item_id: id,
                goods_num: goodsNum
            })
            if (code == 1) {
                this.getCartNum()
                this.$toast({
                    title: msg,
                    icon: 'success'
                })
                this.showSpec = false
            }
        },
        handleConsult() {
            uni.makePhoneCall({
                phoneNumber: this.shop.mobile.toString() //仅为示例
            })
        }
    },
    async onShareAppMessage() {
        const { goodsDetail, inviteCode, team } = this
        return {
            title: team.share_title || goodsDetail.name,
            imageUrl: goodsDetail.image,
            path: '/pages/goods_details/goods_details?id=' + this.id + '&invite_code=' + inviteCode
        }
    },
    computed: {
        ...mapGetters(['cartNum', 'inviteCode', 'sysInfo', 'appConfig', 'userInfo']),
        btnText() {
            const { goodsType } = this
            switch (goodsType) {
                case 1:
                    return {
                        red: '立即抢购',
                        yellow: ''
                    }
                case 2:
                    return {
                        red: '立即开团',
                        yellow: '单独购买'
                    }
                default:
                    return {
                        red: '立即购买',
                        yellow: '加入购物车'
                    }
            }
        },
        getTeamCountTime() {
            return (time) => time - Date.now() / 1000
        },
        navHeight() {
            return this.sysInfo.navHeight
        },
        enableCommission() {
            const {
                goodsType,
                distribution: { earnings, is_show }
            } = this
            return goodsType == 0 && earnings > 0 && is_show == 1
        }
    }
}
</script>

<style lang="scss" scoped>
@import '@/styles/base.scss';

.goods-details {
    padding-bottom: calc(120rpx + env(safe-area-inset-bottom));

    .seckill {
        // height: 100rpx;
        // background: #ffd4d8;

        .price {
            width: 504rpx;
            height: 100%;
            // background: url(../../static/images/bg_seckill.png) no-repeat;
            background-size: 100%;
        }

        .down {
            flex: 1;
        }
    }

    .group {
        // height: 100rpx;
        width: 100%;
        // background-image: url(../../static/images/pintuan_bg.png);
        background-size: 100%;

        .group-num {
            border: 1px solid #ffffff;
            border-radius: 4rpx;

            .group-icon {
                background: #fff;
                padding: 3rpx 7rpx;
            }
        }

        .down {
            height: 100%;
            background-color: #fff5e1;
            padding: 0 20rpx;
        }
    }

    .goods-info {
        position: relative;
        padding: 20rpx;
        .info-header {
            // padding: 20rpx 0 0rpx 24rpx;

            .price {
                align-items: baseline;
            }
        }

        .name {
            // padding: 20rpx 24rpx;
            flex: 1;
        }

        .icon-share {
            width: 134rpx;
            height: 60rpx;
        }
        .vip-price {
            margin: 0 24rpx;
            background-color: #ffe9ba;
            line-height: 36rpx;
            border-radius: 6rpx;
            overflow: hidden;

            .price-name {
                background-color: #101010;
                padding: 3rpx 12rpx;
                color: #ffd4b7;
                position: relative;
                overflow: hidden;

                &::after {
                    content: '';
                    display: block;
                    width: 20rpx;
                    height: 20rpx;
                    position: absolute;
                    right: -15rpx;
                    background-color: #ffe9ba;
                    border-radius: 50%;
                    top: 50%;
                    transform: translateY(-50%);
                    box-sizing: border-box;
                }
            }
        }
    }

    .details-null {
        padding-top: 140rpx;
        margin-bottom: 100rpx;
    }

    .spec {
        padding: 24rpx 24rpx;

        .text {
            width: 100rpx;
        }
    }

    .evaluation {
        .title {
            height: 100rpx;
            border-bottom: $-solid-border;
            padding: 0 24rpx;
        }

        .con {
            padding: 30rpx 24rpx;
        }

        .user-info .avatar {
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
        }
    }

    .details {
        // overflow: hidden;
        .title {
			margin-left: 40rpx;
            line-height: 88rpx;
			color: #333;
        }

        & > .content {
            padding: 0 20rpx 20rpx;

            ::v-deep image {
                vertical-align: middle;
            }

            // #ifdef H5
            ::v-deep img {
                vertical-align: middle;
            }

            // #endif
            // #ifdef MP-WEIXIN || APP-PLUS
            ::v-deep ._img {
                display: block;
            }

            // #endif
        }
    }

    .footer {
        height: 100rpx;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        box-sizing: content-box;
        padding-bottom: env(safe-area-inset-bottom);

        .btn {
            width: 100rpx;
            height: 100rpx;
            position: relative;
            line-height: 1.3;
        }

        .cart-num {
            position: absolute;
            left: 60rpx;
            top: 6rpx;
        }

        .add-cart,
        .right-buy,
        .consult-btn {
            flex: 1;
            text-align: center;
            padding: 16rpx 0;
        }

        .add-cart {
            background-color: #ffa630;
        }

        .right-buy {
            background-color: $-color-primary;
        }
        .consult-btn {
            background: linear-gradient(to right, #ff8e00 0%, #ff2c3c 100%);
        }
    }

    .group-play {
        .title {
            padding: 20rpx 28rpx;
            border-bottom: $-solid-border;
        }

        .steps {
            padding: 20rpx 28rpx;

            .step {
                flex: none;
            }

            .line {
                flex: 1;
                border: 1px dashed #999999;
                margin: 0 20rpx;
            }

            .number {
                border: 1rpx solid #707070;
                width: 28rpx;
                height: 28rpx;
                border-radius: 50%;
                line-height: 28rpx;
                text-align: center;
                margin-right: 6rpx;
            }
        }
    }

    .group-list {
        .group-item {
            padding: 20rpx 24rpx;

            &:not(:last-of-type) {
                border-bottom: $-solid-border;
            }

            .group-btn {
                background: linear-gradient(90deg, #f95f2f 0%, #ff2c3c 100%);
                height: 58rpx;
                padding-left: 28rpx;
                padding-right: 28rpx;
                margin-left: 30rpx;
                box-shadow: 0px 6rpx 12rpx rgba(249, 47, 138, 0.4);
            }
        }
    }

    .share-money {
        position: fixed;
        left: 20rpx;
        bottom: calc(130rpx + env(safe-area-inset-bottom));
        transform: scale(0);
        transition: all 0.3s;

        &.show {
            transform: scale(1);
        }

        .share-close {
            width: 34rpx;
            height: 34rpx;
            background: #a7a7a7;
            border-radius: 50%;
        }

        .share-con {
            background: url('../../static/images/bg_packet_img.png');
            width: 241rpx;
            height: 208rpx;
            background-size: 100%;
            padding-top: 20rpx;
            text-align: center;
        }
    }
}
.round-box {
    border-radius: 20rpx;
}
.bg-vip {
    background: url()
        no-repeat;
    background-size: contain;
    height: 240rpx;
    padding: 30rpx 24rpx;

    .vip-name {
        font-size: 24rpx;
        background-color: #e0a356;
        width: 150rpx;
        border-radius: 25rpx;
        text-align: center;
        line-height: 30rpx;
        padding: 5rpx 0;
        margin-bottom: 10rpx;
        position: relative;

        &::before {
            position: absolute;
            content: '';
            top: -7rpx;
            right: 10rpx;
            width: 0;
            height: 0;
            border-top: 50px solid #e0a356;
            border-right: 50px solid transparent;
            border-left: 50px solid transparent;
            transform: scale(0.15);
        }
    }
}
.bg-team {
    display: flex;
    background: url(../../static/images/temp-bg.png) no-repeat;
    background-size: contain;
    height: 240rpx;
    padding: 30rpx 24rpx;

    .tip {
        font-size: 24rpx;
        color: black;
        background-color: white;
        padding: 5rpx 10rpx;
        border-radius: 10rpx;
        margin-right: 10rpx;
    }

    &__price {
        color: white;
        flex: 1;
        display: flex;
        justify-content: space-between;
        padding: 0 20rpx;
    }

    &__time {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 240rpx;
        // @include background_color(0.3);
    }
}
.bg-seckill {
    display: flex;
    background: url(../../static/images/seckill-bg.png) no-repeat;
    background-size: contain;
    height: 240rpx;
    padding: 30rpx 24rpx;

    .tip {
        font-size: 24rpx;
        color: black;
        background-color: white;
        padding: 5rpx 10rpx;
        border-radius: 10rpx;
        margin-right: 10rpx;
    }

    &__price {
        color: white;
        flex: 1;
        display: flex;
        justify-content: space-between;
        padding: 0 20rpx;
    }

    &__time {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 240rpx;
        // @include background_color(0.3);
    }
}
.shichang-box {
	margin-left: 13rpx;
	font-size: 26rpx;
}
.fenxiang-btn {
	color: #666;
	font-size: 24rpx;
	align-items: center;
	text {
		position: relative;
		top: -2rpx;
		margin-left: 2rpx;
	}
}
.jifen-box {
	font-size: 28rpx;
	color: #0271E4;
	font-weight: 400;
}
.yue-xiao {
	font-size: 24rpx;
	color: #999;
	font-weight: 400;
}
.jiaru-goumai {
	display: flex;
	font-size: 26rpx;
	margin-left: 20rpx;
	.jiaru-box {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 184rpx;
		height: 68rpx;
		background: #3898FC;
		color: white;
		border-top-left-radius: 30rpx;
		border-bottom-left-radius: 30rpx;
	}
	.goumai-box {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 550rpx;
		height: 79rpx;
		background: #0271E4;
		color: white;
		border-radius: 40rpx;
	}
}
.flex-center {
	display: flex;
	align-items: center;
	justify-content: center;
}
.need-gouwuquan {
	font-weight: 400;
	font-size: 24rpx;
	color: #C92121;
	text {
		font-size: 40rpx;
	}
}
.shouhou-box {
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 750rpx;
	height: 120rpx;
	margin-top: 20rpx;
	padding-left: 30rpx;
	padding-right: 40rpx;
	background: #FFFFFF;
	.shouhou-title {
		font-weight: 400;
		font-size: 24rpx;
		color: #999999;
	}
	.miaoshu {
		display: flex;
		align-items: center;
		font-weight: 400;
		font-size: 24rpx;
		color: #333333;
		image {
			margin-left: 10rpx;
			margin-right: 8rpx;
			margin-top: 2rpx;
			width: 22rpx;
			height: 22rpx;
		}
	}
}
</style>
